package com.xxxx.springbootsecurity02.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxx.springbootsecurity02.exception.LoginException;
import com.xxxx.springbootsecurity02.mapper.UserMapper;
import com.xxxx.springbootsecurity02.pojo.LoginUser;
import com.xxxx.springbootsecurity02.pojo.SysUser;
import com.xxxx.springbootsecurity02.service.UserService;
import com.xxxx.springbootsecurity02.util.JwtUtil;
import com.xxxx.springbootsecurity02.util.RedisCache;
import com.xxxx.springbootsecurity02.util.ResultJSON;
import org.apache.ibatis.session.ResultContext;
import org.apache.ibatis.session.ResultHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, SysUser> implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;

    public void liushi() {
        userMapper.selectList(null, new ResultHandler<SysUser>() {
            int count = 0;
            @Override
            public void handleResult(ResultContext<? extends SysUser> resultContext) {
                SysUser sysUser = resultContext.getResultObject();
                System.out.println("当前处理第" + (++count) + "条记录: " + sysUser);
            }
        });
    }

    @Override
    public ResultJSON login(SysUser sysUser) {

        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                new UsernamePasswordAuthenticationToken(sysUser.getUserName(),sysUser.getPassword());

        //返回封装好的userDetails对象
        Authentication authenticate =  authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        if (loginUser == null) {
            throw new LoginException("密码错误-02");
        }
        //将用户对象存入redis缓存
        redisCache.setCacheObject("login:"+loginUser.getSysUser().getId(),loginUser,1, TimeUnit.HOURS);
        //根据用户ID生成token
        String token = JwtUtil.createJWT(loginUser.getSysUser().getId().toString());
        return ResultJSON.success("登录成功",token);
    }
}
